package com.mti.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mti.component.snowflake.KeyWorker;
import com.mti.dao.kmmodel.KmArmingTaskEntity;
import com.mti.dao.model.KmTrailEntity;
import com.mti.dao.model.LfZdryHistoryLogEntity;
import com.mti.dao.model.SysDictEntity;
import com.mti.dao.model.TKmTrailSetEntity;
import com.mti.dao.model.TKmTrailSetRelEntity;
import com.mti.dao.qo.TKmTrailQO;
import com.mti.dao.qo.TKmTrailSetQO;
import com.mti.dao.vo.KmTrailVo;
import com.mti.exception.BusinessException;
import com.mti.jwt.AccountBo;
import com.mti.jwt.RequestUtils;
import com.mti.mapper.TKmTrailSetMapper;
import com.mti.service.ISysDictService;
import com.mti.service.LfZdryHistoryLogService;
import com.mti.service.TKmTrailSetService;
import com.mti.utils.GetRemoteIpUtil;

import io.jsonwebtoken.lang.Collections;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;


/**
 * @Classname TKmTrailSetServiceImpl
 * @Description TODO
 * @Date 2020/1/17 23:18
 * @Created by duchaof
 * @Version 1.0
 */
@Service
public class TKmTrailSetServiceImpl extends ServiceImpl<TKmTrailSetMapper, TKmTrailSetEntity> implements  TKmTrailSetService {
	
	@Resource
	private TKmTrailSetMapper tkmtrailsetMapper;
	
	@Autowired
    private ISysDictService service;
	
	@Autowired
	private LfZdryHistoryLogService lfZdryHistoryLogService;
	
	@Autowired
	private GetRemoteIpUtil getRemoteIpUtil;
	
	@Autowired
	private RequestUtils requestUtils;
	
	
	@Override
	public boolean saveTKmTrailSet(TKmTrailSetEntity entity,ServerWebExchange exchange) {
		if(entity == null) {
			throw new BusinessException(500,"数据为空");
		}
		boolean flag = false;
		String personType = entity.getPersonType();
		if(null == entity.getId()) {
		String id = String.valueOf(KeyWorker.nextId());
		entity.setId(id);
		entity.setCreateTime(new Date());
		entity.setIsUse("1");
		entity.setIsDelete("0");
		int index = tkmtrailsetMapper.insert(entity);
		if(index==1) {flag = true;}
		//人员类型添加
		if(StringUtils.isNotEmpty(personType)) {
			flag = personTypeRel(personType,id);
			this.operatLog("新增", entity, "新增模型配置",exchange);
		 }
		}else {
			tkmtrailsetMapper.updateById(entity);
			int updateTKmTrailSet = tkmtrailsetMapper.updateTKmTrailSet(entity);
			this.operatLog("修改", entity, "修改模型配置",exchange);
			if(updateTKmTrailSet == 1) {flag = true;}
			//清空中间数据表
			if(StringUtils.isNotEmpty(personType)) {
				tkmtrailsetMapper.deleteRelPersonType(entity.getId());
				//人员类型添加
				flag = personTypeRel(personType,entity.getId());
			}
		}
		return flag;
	}
		//重点人员类型关联表
		public boolean  personTypeRel(String personType,String id) {
			boolean flag = false;
			JSONArray json = (JSONArray) JSONArray.parse(personType);
			TKmTrailSetRelEntity relEntity = new TKmTrailSetRelEntity();;
			for (Object obj : json) {
				  JSONObject jo = (JSONObject)obj;
				  relEntity.setSetId(id); 
				  String code = jo.getString("code");
				  relEntity.setMaxClassCode(code);
				  relEntity.setMaxClassName(jo.getString("name"));
				  String children = jo.getString("children");
				  if(StringUtils.isNotEmpty(children) && !children.equals("[]")) {
					  JSONArray json1 = (JSONArray) JSONArray.parse(children);
					  for (Object obj1 : json1) {
						  JSONObject jo1 = (JSONObject)obj1;
						  relEntity.setId(String.valueOf(KeyWorker.nextId()));
						  relEntity.setSmallClassCode(jo1.getString("code"));
						  relEntity.setSmallClassName(jo1.getString("name"));
						  int index = tkmtrailsetMapper.insertRelPersonType(relEntity); 
						  if(index == 1) {flag = true;}
					  }
				}else {
					List<SysDictEntity> list = service.getByType(code);
					if(list.size()>0 && list != null) {
						for(int i = 0;i < list.size();i++) {
							relEntity.setId(String.valueOf(KeyWorker.nextId()));
							relEntity.setSmallClassCode(list.get(i).getKey());
							relEntity.setSmallClassName(list.get(i).getValue());
							int index = tkmtrailsetMapper.insertRelPersonType(relEntity); 	
							if(index == 1) {flag = true;}
						}
					}
				}
			}
			return flag;
		}

	@Override
	public Integer deleteTKmTrailSet(String id,ServerWebExchange exchange) {
		TKmTrailSetEntity entity = new TKmTrailSetEntity();
		entity.setId(id);
		entity.setIsDelete("1");
		this.operatLog(id,exchange);
		return tkmtrailsetMapper.updateById(entity);
	}

	@Override
	public Integer stop(String id) {
		TKmTrailSetEntity entity = new TKmTrailSetEntity();
		entity.setId(id);
		entity.setIsUse("0");
		return tkmtrailsetMapper.updateById(entity);
	}

	@Override
	public Integer start(String id) {
		TKmTrailSetEntity entity = new TKmTrailSetEntity();
		entity.setId(id);
		entity.setIsUse("1");
		return tkmtrailsetMapper.updateById(entity);
	}

	@Override
	public IPage<TKmTrailSetEntity> queryPageList(TKmTrailSetQO qo) {
		Page<TKmTrailSetEntity> page = new Page<>(qo.getStart(), qo.getSize());
		return tkmtrailsetMapper.queryPage(page, qo);
	}
	@Override
	public IPage<KmTrailEntity> getPageList(TKmTrailQO qo) {
		Page<KmTrailEntity> page = new Page<>(qo.getStart(), qo.getSize());
		return tkmtrailsetMapper.getPageList(page, qo);
	}
	
	/**
	 * 操作日志方法
	 * @param type
	 * @param bo
	 * @param entity
	 * @param logRecord
	 * @return
	 */
	public void operatLog(String type,TKmTrailSetEntity entity,String logRecord,ServerWebExchange exchange) {
   		//历史记录
		AccountBo bo = requestUtils.getCurrentUser(exchange);
			if(bo==null) {
				throw new BusinessException(10019,"此账号已在别处登录，请查证");
			}
   		LfZdryHistoryLogEntity history = new LfZdryHistoryLogEntity();
        history.setCreator(bo.getPersonBo().getName());
        history.setCreatorCode(bo.getPersonBo().getPoliceCode());
        history.setCreateTime(new Date());
   		history.setSpId(entity.getId());
   		history.setApproveResult(logRecord);
   		history.setOperation(type);
   		history.setOperateDept(bo.getOrganizationBo().getShortName());
   		history.setFunctionModule("情报线索模块");

		ServerHttpRequest request = exchange.getRequest();
		String ip = getRemoteIpUtil.getRemoteIP(request);
		history.setOperateIp(ip);
		//变更
		history.setType(3);
   		lfZdryHistoryLogService.save(history);
	}
	@Override
	public List<KmTrailVo> getAllList(String type) {
		return tkmtrailsetMapper.getAllList(type);
	}
	@Override
	public Integer updateStatusById(String id) {
		return tkmtrailsetMapper.updateStatusById(id);
	}
	public void operatLog(String id,ServerWebExchange exchange) {
		AccountBo bo = requestUtils.getCurrentUser(exchange);
			if(bo==null) {
				throw new BusinessException(10019,"此账号已在别处登录，请查证");
			}
		//历史记录
   		LfZdryHistoryLogEntity history = new LfZdryHistoryLogEntity();
        history.setCreator(bo.getPersonBo().getName());
        history.setCreateTime(new Date());
   		history.setSpId(id);
   		history.setApproveResult("删除模型配置");
   		history.setOperation("删除");
   		history.setOperateDept(bo.getOrganizationBo().getShortName());
   		history.setFunctionModule("情报线索模块");

		ServerHttpRequest request = exchange.getRequest();
		String ip = getRemoteIpUtil.getRemoteIP(request);
		history.setOperateIp(ip);
		//变更
		history.setType(3);
   		lfZdryHistoryLogService.save(history);
	}
	

}
